package cn.vastbase.jdbc.io;

import cn.com.vastbase.bulkload.BulkloadManager;
import cn.com.vastbase.jdbc.PgConnection;
import org.junit.Test;

import java.io.File;
import java.net.URL;
import java.sql.*;

/**
 * 使用Bulkload API导入文本文件到数据库
 */
public class BulkloadTestCase {

    static Connection conn = null;
    static String cname = "org.postgresql.Driver";
    static String url = "jdbc:postgresql://192.168.56.12:6000/test?loggerLevel=trace";
    static String username = "test";
    static String passwd = "Vastdata#0730";
    static Statement stmt = null;
    static PreparedStatement pstmt = null;
    static ResultSet rs = null;

    public Connection conn() {
        try {
            Class.forName(cname);
            return conn = DriverManager.getConnection(url, username, passwd);
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("[FAIL] conn database fail." + e.getMessage());
        }
        return null;
    }

    public void close() {
        try {
            /* 关闭结果集对象 */
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close resultSet fail." + e.getMessage());
        }
        try {
            /* 关闭语句对象 */
            if (stmt != null)
                stmt.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close statement fail." + e.getMessage());
        }
        try {
            /* 关闭语句对象 */
            if (pstmt != null)
                pstmt.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close statement fail." + e.getMessage());
        }
        try {
            /* 关闭连接 */
            if (pstmt != null)
                conn.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close connection fail." + e.getMessage());
        }
    }


    /**
     * 2.10驱动还有bug，不能使用
     * throws SQLException
     */
    @Test
    public void testBulkloadWithServerLocalFileInput() throws SQLException {
        ClassLoader classLoader = BulkloadTestCase.class.getClassLoader();
        URL resource = classLoader.getResource("bulkload.ctl");
        File file = new File(resource.getFile());
        String absolutePath = file.getAbsolutePath();
        url += "&bulkloadCtlFile=" + absolutePath;
        if (conn() == null)
            return;
        BulkloadManager bulkloadAPI = ((PgConnection) conn).getBulkloadAPI();
        try {
            rs = bulkloadAPI.bulkloadIn();
            while (rs.next()) {
                for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) {
                    System.out.println(rs.getMetaData().getColumnLabel(i) + ":" + rs.getObject(rs.getMetaData().getColumnLabel(i)));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }

}
